I was trying to easily convert back and forth between C-syntax Hex and Ascii (used a lot in Arduino, because apparently that's a fun way to store web pages on embedded controllers), and stumbled upon this thread. It was useful to completing my task, so thought it worth giving back. If nothing else, when I need to do this for something else and misplace these little utils, perhaps my web search will bring me here.
The following scriptlettes should be rather light weight and only use fairly standard POSIX utils (od, sed, bash).
$ cat asc2hex
Code:
#!/bin/bash
while read line; do
echo $line|od -An -tx1|sed 's/ /, 0x/g;s/^, //;s/$/,/'
done < "${1:-/dev/stdin}"
exit 0
$ cat hex2asc
Code:
#!/bin/bash
while read line; do
echo -en `echo $line|sed 's/, 0x/\\\\x/g;s/^0x/\\\\x/;s/,$//'`
done < "${1:-/dev/stdin}"
exit 0
Example usage:
Code:
$ echo "Hello World!"|./asc2hex
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x0a,
$ echo "Hello World!"|./asc2hex|./hex2asc
Hello World!
Alternatively, scriptlettes will also accept direct file as an option:
Code:
$ cat hello_world
Hello World!
$ ./asc2hex hello_world
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x0a,
$ ./asc2hex hello_world|./hex2asc
Hello World!